package com.atguigu.spzx.manager.service.impl;

import com.atguigu.spzx.common.handler.exception.SpzxException;
import com.atguigu.commom.utils.ThreadLocalUtil;
import com.atguigu.spzx.manager.mapper.SysMenuMapper;
import com.atguigu.spzx.manager.service.SysMenuService;
import com.atguigu.spzx.model.common.ResultCodeEnum;
import com.atguigu.spzx.model.entity.sys.SysMenu;
import com.atguigu.spzx.model.entity.sys.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * title:
 * author: zgl
 * date: 2023/12/30
 * description：
 */
@Service
public class SysMenuServiceImpl implements SysMenuService {
    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public List<SysMenu> getMenuList() {
        List<SysMenu> sysMenuList = sysMenuMapper.getMenuList();
        //一级菜单
        //不能使用==  会出现问题  多级菜单层级调用  递归或者动态规划
        List<SysMenu> oneMenuList = sysMenuList.stream().filter(item -> item.getParentId() == 0).collect(Collectors.toList());
        getMenuTree(sysMenuList, oneMenuList);
        return oneMenuList;
    }

    //封装方便调用
    private void getMenuTree(List<SysMenu> sysMenuList, List<SysMenu> oneMenuList) {
        if (CollectionUtils.isEmpty(oneMenuList)) {
            return;
        }
        oneMenuList.forEach(oneMenu -> {
            List<SysMenu> twoMenuList = sysMenuList.stream().filter(item -> item.getParentId() == oneMenu.getId()).collect(Collectors.toList());
            oneMenu.setChildren(twoMenuList);
        });
    }

    @Override
    public void saveFatherMenu(SysMenu sysMenu) {
        sysMenuMapper.saveFatherMenu(sysMenu);
    }

    @Override
    public void deleteMenu(Long id) {
        //需先判断有没有子路由
        boolean flag = sysMenuMapper.hasChildren(id);
        if (flag) {
            throw new SpzxException(ResultCodeEnum.HAS_CHILDREN_ERROR);
        }
        sysMenuMapper.deleteMenu(id);
    }

    /*  @Override
      public void saveSonMenu(SysMenu sysMenu) {
          sysMenuMapper.saveSonMenu(sysMenu);
      }
  */
    @Override
    public void updateMenu(SysMenu sysMenu) {
        sysMenuMapper.updateMenu(sysMenu);
    }

    @Override
    public List<SysMenu> getMenus() {
        //从本地线程变量中获取用户的id
        SysUser sysUser = ThreadLocalUtil.threadLocal.get();
        Long userId = sysUser.getId();
        //查询对应id对应的所有菜单信息
        List<SysMenu> sysMenuList = sysMenuMapper.getMenus(userId);
        //包装数据
        List<SysMenu> oneMenuList = sysMenuList.stream().filter(oneMenu -> oneMenu.getParentId().equals(0L)).collect(Collectors.toList());
        getMenuTree(sysMenuList, oneMenuList);
        return oneMenuList;
    }
}
